package com.dyava.commons.defaultvalue;

import javassist.CannotCompileException;
import javassist.NotFoundException;

import java.beans.IntrospectionException;

/**
 * 创建默认值的工具类
 */
public class DefaultValueUtils {
	private static DefaultValueBuilderFactory defaultValueBuilderFactory = new DefaultValueBuilderFactory();

	/**
	 * 根据class生成带默认值的对象
	 * @param clazz
	 * @param <T>
	 * @return
	 */
	public static <T> T create(Class<T> clazz){
		try {
			DefaultValueBuilder defaultValueBuilder = defaultValueBuilderFactory.getDefaultValueBuilder(clazz);
			Object obj = defaultValueBuilder.create();
			return (T)obj;
		} catch (InstantiationException | IllegalAccessException | NotFoundException | CannotCompileException | IntrospectionException e) {
			throw new DefaultValueRuntimeException(e);
		}
	};

	/**
	 * 强制填充带默认值的对象，覆盖已有值
	 * @param obj
	 * @param <T>
	 * @return
	 */
	public static <T> T fillForce(T obj){
		try {
			DefaultValueBuilder defaultValueBuilder =  defaultValueBuilderFactory.getDefaultValueBuilder(obj.getClass());
			defaultValueBuilder.fillForce(obj);
			return obj;
		} catch (InstantiationException | IllegalAccessException | NotFoundException | CannotCompileException | IntrospectionException e) {
			throw new DefaultValueRuntimeException(e);
		}
	};

	/**
	 * 填充带默认值的对象，不覆盖已有值
	 * @param obj
	 * @param <T>
	 * @return
	 */
	public static <T> T fillSafe(T obj){
		try {
			DefaultValueBuilder defaultValueBuilder =  defaultValueBuilderFactory.getDefaultValueBuilder(obj.getClass());
			defaultValueBuilder.fillSafe(obj);
			return obj;
		} catch (InstantiationException | IllegalAccessException | NotFoundException | CannotCompileException | IntrospectionException e) {
			throw new DefaultValueRuntimeException(e);
		}
	};
}
